/**
 * 简化的API服务类
 * 统一处理所有数据库连接请求
 */

const config = require('./config');

class APIService {
  constructor() {
    this.baseURL = config.api.baseURL;
    this.timeout = config.api.timeout;
    this.retryTimes = config.api.retryTimes;
  }

  /**
   * 通用请求方法
   */
  request(method, endpoint, data = null, params = {}) {
    return new Promise((resolve, reject) => {
      const url = this.buildURL(endpoint, params);
      
      wx.request({
        url,
        method,
        data,
        timeout: this.timeout,
        header: {
          'Content-Type': 'application/json'
        },
        success: (res) => {
          if (res.statusCode === config.statusCodes.SUCCESS) {
            resolve(res.data);
          } else {
            reject(new Error(this.getErrorMessage(res.statusCode)));
          }
        },
        fail: (err) => {
          reject(new Error(this.getErrorMessage(err)));
        }
      });
    });
  }

  /**
   * 构建URL
   */
  buildURL(endpoint, params = {}) {
    const url = `${this.baseURL}${endpoint}`;
    if (Object.keys(params).length === 0) return url;
    
    const queryString = Object.keys(params)
      .map(key => `${key}=${encodeURIComponent(params[key])}`)
      .join('&');
    
    return `${url}?${queryString}`;
  }

  /**
   * 获取错误消息
   */
  getErrorMessage(error) {
    if (typeof error === 'number') {
      switch (error) {
        case config.statusCodes.BAD_REQUEST:
          return '请求参数错误';
        case config.statusCodes.UNAUTHORIZED:
          return '未授权访问';
        case config.statusCodes.FORBIDDEN:
          return '访问被拒绝';
        case config.statusCodes.NOT_FOUND:
          return '资源不存在';
        case config.statusCodes.SERVER_ERROR:
          return config.messages.serverError;
        default:
          return config.messages.unknownError;
      }
    }
    
    if (error.errMsg) {
      if (error.errMsg.includes('timeout')) {
        return config.messages.timeoutError;
      }
      if (error.errMsg.includes('fail')) {
        return config.messages.networkError;
      }
    }
    
    return error.message || config.messages.unknownError;
  }

  // HTTP方法
  get(endpoint, params = {}) {
    return this.request('GET', endpoint, null, params);
  }

  post(endpoint, data = {}) {
    return this.request('POST', endpoint, data);
  }

  put(endpoint, data = {}) {
    return this.request('PUT', endpoint, data);
  }

  delete(endpoint) {
    return this.request('DELETE', endpoint);
  }

  // ==================== 业务接口 ====================
  
  // 闲置物品相关
  getIdleItems(params = {}) {
    return this.get('/idle-items', params);
  }

  createIdleItem(data) {
    return this.post('/idle-items', data);
  }

  getIdleItemDetail(id) {
    return this.get(`/idle-items/${id}`);
  }

  // 技能共享相关
  getSkills(params = {}) {
    return this.get('/skills', params);
  }

  createSkill(data) {
    return this.post('/skills', data);
  }

  getSkillDetail(id) {
    return this.get(`/skills/${id}`);
  }

  // 借用请求相关
  createBorrowRequest(data) {
    return this.post('/borrow-requests', data);
  }

  /**
   * 提交借用申请
   */
  submitBorrowApplication(data) {
    return this.createBorrowRequest(data);
  }

  getBorrowRequests(params = {}) {
    return this.get('/borrow-requests', params);
  }

  // 用户相关
  getUserInfo(userId) {
    return this.get(`/users/${userId}`);
  }

  createUser(data) {
    return this.post('/users', data);
  }

  // 通知相关
  getNotices(params = {}) {
    return this.get('/notices', params);
  }

  createNotice(data) {
    return this.post('/notices', data);
  }

  // 分类相关
  getCategories() {
    return this.get('/categories');
  }

  // ==================== 工具方法 ====================
  
  /**
   * 统一错误处理
   */
  handleError(error, fallbackData = null) {
    console.error('API请求错误:', error);
    
    // 显示错误提示
    wx.showToast({
      title: error.message || config.messages.unknownError,
      icon: 'none',
      duration: 2000
    });

    // 返回备用数据
    return fallbackData;
  }

  /**
   * 成功提示
   */
  showSuccess(message = config.messages.success) {
    wx.showToast({
      title: message,
      icon: 'success',
      duration: 2000
    });
  }

  /**
   * 带错误处理的请求包装器
   */
  async safeRequest(requestFn, fallbackData = null) {
    try {
      console.log('尝试执行API请求');
      const result = await requestFn();
      console.log('API请求成功，返回数据:', result);
      return result;
    } catch (error) {
      console.error('API请求失败，使用模拟数据:', error);
      return this.handleError(error, fallbackData);
    }
  }

  /**
   * 带重试的请求
   */
  async requestWithRetry(requestFn, maxRetries = this.retryTimes) {
    for (let i = 0; i < maxRetries; i++) {
      try {
        return await requestFn();
      } catch (error) {
        if (i === maxRetries - 1) {
          throw error;
        }
        // 等待一段时间后重试
        await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
      }
    }
  }
}

// 创建单例实例
const apiService = new APIService();

module.exports = apiService;